package com.leenmvc.core.utils.collection;

import java.lang.reflect.Array;
import java.util.*;

public class ArrayUtils {

    public static <T> boolean contain(T[] ts, T t) {
        if(ts == null) return false;
        for(T item: ts) {
            if(item.equals(t)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 清空为null值的item
     *
     * @param list
     * @param <T>
     * @return
     */
    public static <T> List<T> clearNull(List<T> list) {
        List<T> result = new ArrayList<>();
        for(T t: list) {
            if(t != null) {
                result.add(t);
            }
        }
        return result;
    }



    /**
     * 清空为null值的item
     *
     * @param source
     * @param <T>
     * @return
     */
    public static <T> T[] clearNull(T[] source) {
        T[] result = (T[])Array.newInstance(source[0].getClass(), 0);
        for(int i = 0; i < source.length; i++) {
            if(source[i] != null) {
                result = Arrays.copyOf(result, result.length + 1);
                result[result.length - 1] = source[i];
            }
        }
        return result;
    }

    /**
     * 清空为null值的item
     *
     * @param source
     * @param <T>
     * @return
     */
    public static <T> Set<T> clearNull(Set<T> source) {
        Set<T> result = new HashSet<>();
        for(T t: source) {
            if(t != null) {
                result.add(t);
            }
        }
        return result;
    }

    /**
     * 添加一个记录到数组中
     *
     * @param t
     * @param <T>
     * @return
     */
    public static <T> T[] arrayAdd(T[] ts, T t) {
        T[] ts1 = Arrays.copyOf(ts, ts.length + 1);
        ts1[ts1.length - 1] = t;
        return ts1;
    }

    /**
     * 添加多条记录到数组中
     *
     * @param ts
     * @param tAdd
     * @param <T>
     * @return
     */
    public static <T> T[] arrayAddAll(T[] ts, T[] tAdd) {
        T[] ts1 = Arrays.copyOf(ts, ts.length + tAdd.length);
        for(int i = tAdd.length - 1 ; i >= 0; i--) {
            ts1[ts1.length - i - 1] = tAdd[tAdd.length - 1 - i];
        }
        return ts1;
    }
}
